/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

/**
 *
 * @author mx109
 */
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.SecretKey;
import security.*;
import others.*;
 
public class MyClient {
 
  String serverurl = "127.0.0.1";
  int serverport = 8180;
  Socket socket = null;
   InputStreamReader inputstreamreader;
  BufferedReader bufferedreader;
  PrintWriter printwriter;        
  PublicKey serverPublicKey;
  SecretKey myKey;
  String path="certifikat";
  
          
  public static void main(String[] args){
    MyClient simpleclient = new MyClient();
    simpleclient.init();
  }
 
  
  
  void polacz() throws UnknownHostException, SocketException, IOException{
    System.out.println("Łączenie z " + serverurl + " na porcie " + serverport);
      socket = new Socket(serverurl,serverport);
      socket.setSoTimeout(1000000);
     
      inputstreamreader = new InputStreamReader(socket.getInputStream());
       bufferedreader = new BufferedReader(inputstreamreader);
       printwriter = new PrintWriter(socket.getOutputStream(),true);
        System.out.println("Połączono.");
  }
  
  void rozlacz() throws IOException{
      bufferedreader.close();
      inputstreamreader.close();
      printwriter.close();
      socket.close();
      
  }
  
  void handshake() throws UnknownHostException, Exception{ //funkcja przełącza połączenie na odpowiedni port i pobiera klucz prywatny serwera
        polacz();
      String lineread = bufferedreader.readLine();
      
      String lineread2 = bufferedreader.readLine();
      serverPublicKey = (PublicKey) Serializator.deserialize(lineread2);
      System.out.println("Przekierowywanie na port: "+lineread+" klucz: "+serverPublicKey);
        rozlacz();
      serverport = Integer.parseInt(lineread);
      polacz();
      myKey = SymmetricCipher.getKey();
      
      String s1ey = Serializator.serializ(myKey);
      System.out.println("Wysyłam następujący klucz symetryczny: "+s1ey);
      byte[] code = AsymmetricCipher.encrypt(s1ey.getBytes(), serverPublicKey);
     // String sley = new String(code, "UTF8");
       String tosend = Serializator.serializ(code);
      printwriter.println(tosend);
      
  }
  
  void sendText(String s){
   try{
      byte[] tekst = SymmetricCipher.encrypt(s.getBytes(), myKey);
      String tosend = Serializator.serializ(tekst);
      //System.out.println("Wysyłam:"+tekst+ " =>" + new String(SymmetricCipher.decrypt(tekst, myKey))+"\n"+tosend);
      printwriter.println(tosend);
   }catch(Exception e){System.out.println("Send error:"+e);}
   
  
  }
  
   String getText() {
        try {
            String lineread;
            lineread = bufferedreader.readLine();
            if (lineread==null) return null;
            lineread=new String(    SymmetricCipher.decrypt((byte[])Serializator.deserialize(lineread),myKey  ),"UTF8"  );
            return lineread;
        } catch (Exception ex) {Logger.getLogger(OwnServer.class.getName()).log(Level.SEVERE, null, ex); return null; }
       
    }
   
   void printText(){
        String lineread;
       lineread = getText();
        System.out.println(":>" + lineread);
      
   }
   
  public void init(){
      
    try{
     handshake();
      
      Scanner in = new Scanner(System.in);
      String text = "t";
      while(!(text.equals("koniec"))){
          
      text = in.nextLine();
      if (text.equals("dajcertyfikat")) {
          sendText(text);
          String cert = getText();
          Serializator.saveObject(cert, path);
          System.out.println("Zapisano certyfikat");
      }else
      if (text.equals("sprawdzcertyfikat")) {
          sendText(text);
          String cert = (String) Serializator.loadObject(path);
          sendText(cert);
          System.out.println("Wysłałem");
          printText();
      }
      else
      if (text.equals("/sciezka")){
      path=in.nextLine();
      }
      else{
        sendText(text);
        printText();
      }
      
      }
      
      rozlacz();
      
      System.exit(0);
 
    }catch(UnknownHostException unhe){
      System.out.println("UnknownHostException: " + unhe.getMessage());
    }catch(InterruptedIOException intioe){
      System.out.println("Timeout while attempting to establish socket connection.");
    }catch(Exception ioe){
      System.out.println("IO: " + ioe.getMessage());
    }finally{
      try{
        socket.close();
      }catch(Exception ioe){
        System.out.println(ioe.getMessage());
      }
    }
  }      
}
